<template>
  <el-drawer
    :append-to-body="true"
    title="条件设置"
    v-model="visible"
    class="condition_expression"
    :show-close="false"
    :size="600"
    :before-close="saveCondition"
  >
    <template #header="{ titleId, titleClass }">
      <h3 :id="titleId" :class="titleClass">条件设置</h3>
      <select v-model="conditionConfig.priorityLevel" class="priority_level">
        <option v-for="item in conditionsConfig.conditionNodes.length" :value="item" :key="item">
          优先级{{ item }}
        </option>
      </select>
    </template>
    
    <div class="demo-drawer__content">
      <div class="condition_content drawer_content">
        <p class="tip">当审批单满足以下条件表达式时进入此流程</p>
        
        <!-- 条件表达式输入区域 -->
        <div class="expression-input-section">
          <el-form-item label="表达式" required>
            <div class="expression-controls">
              <el-switch
                v-model="showSyntaxDoc"
                active-text="显示语法文档"
                inactive-text="隐藏语法文档"
                style="margin-bottom: 12px;"
              />
            </div>
            <ExpressionEditor
              v-model="conditionConfig.condition"
              :system-variables="systemVariables"
              :form-variables="formVariables"
              :show-variable-help="true"
              :show-example="!showSyntaxDoc"
              :show-syntax-doc="showSyntaxDoc"
              placeholder="请输入条件表达式，例如：creator == 'admin' && amount > 1000"
              @validate="handleValidationResult"
            />
          </el-form-item>
        </div>
      </div>
      
      <div class="demo-drawer__footer clear">
        <el-button type="primary" @click="saveCondition">确 定</el-button>
        <el-button @click="closeDrawer">取 消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, inject, watch } from 'vue'
import { ElMessage } from 'element-plus'
import $func from '../utils/index'
import ExpressionEditor from '../../ExpressionEditor/ExpressionEditor.vue'

const props = defineProps({
  internalState: {
    type: Object,
    default: null,
  },
})

// 获取内部状态管理
const flowDesignerState = inject('flowDesignerState', null)
const state = flowDesignerState.state
const actions = flowDesignerState.actions
const { formConfig } = flowDesignerState

// 响应式数据
const conditionsConfig = ref({
  conditionNodes: [],
})
const conditionConfig = ref({
  condition: '', // 条件表达式
})
const showSyntaxDoc = ref(false)
const currentValidationResult = ref(null)

// 系统变量
const systemVariables = ref([
  { name: 'creator', label: '发起人', type: 'string' }
])

// 表单变量（从formConfig中获取）
const formVariables = computed(() => {
  if (!formConfig?.fields) return []
  return formConfig.fields.map(field => ({
    name: field.name,
    label: field.label,
    type: getVariableType(field.type),
  }))
})

// 将表单字段类型转换为ExpressionEditor支持的类型
const getVariableType = (fieldType) => {
  const typeMap = {
    text: 'string',
    textarea: 'string',
    number: 'number',
    select: 'string',
    radio: 'string',
    checkbox: 'array',
    date: 'string',
    datetime: 'string',
    file: 'string',
  }
  return typeMap[fieldType] || 'string'
}

// 计算属性
const conditionsConfig1 = computed(() => state.conditionsConfig1)
const conditionDrawer = computed(() => state.conditionDrawer)
const visible = computed({
  get() {
    return conditionDrawer.value
  },
  set() {
    closeDrawer()
  },
})

// 监听配置变化
watch(conditionsConfig1, (val) => {
  conditionsConfig.value = val.value
  conditionConfig.value = val.priorityLevel
    ? conditionsConfig.value.conditionNodes[val.priorityLevel - 1]
    : { condition: '' }
})

// 处理ExpressionEditor的验证结果
const handleValidationResult = (result) => {
  currentValidationResult.value = result
  // 可以在这里处理验证结果，比如显示消息或更新状态
  if (result.isValid) {
    // 表达式有效
    console.log('表达式验证通过')
  } else if (result.errors.length > 0) {
    // 表达式有错误
    console.log('表达式验证失败:', result.errors)
  }
}

// 调整条件节点优先级顺序
const adjustConditionNodesPriority = (originalPriorityLevel, newPriorityLevel) => {
  if (!originalPriorityLevel || !newPriorityLevel || originalPriorityLevel === newPriorityLevel) {
    return
  }
  
  const currentIndex = originalPriorityLevel - 1
  const targetIndex = newPriorityLevel - 1
  
  // 移动数组元素到新位置
  const currentNode = conditionsConfig.value.conditionNodes[currentIndex]
  conditionsConfig.value.conditionNodes.splice(currentIndex, 1)
  conditionsConfig.value.conditionNodes.splice(targetIndex, 0, currentNode)
  
  // 重新设置所有节点的priorityLevel
  conditionsConfig.value.conditionNodes.forEach((item, index) => {
    item.priorityLevel = index + 1
  })
}

// 保存条件
const saveCondition = () => {  
  // 检查表达式是否有效
  if (currentValidationResult.value && !currentValidationResult.value.isValid) {
    const errorMessages = currentValidationResult.value.errors.map(error => error.message).join('；')
    ElMessage.error(`表达式验证失败：${errorMessages}`)
    return
  }
  
  // 调整优先级顺序
  adjustConditionNodesPriority(
    conditionsConfig1.value.priorityLevel,
    conditionConfig.value.priorityLevel
  )
  
  // 设置错误状态（如果表达式为空）
  conditionConfig.value.error =
    $func.expressionConditionStr(conditionsConfig.value, conditionConfig.value.priorityLevel - 1) ==
      '请设置条件' &&
    conditionConfig.value.priorityLevel != conditionsConfig.value.conditionNodes.length
  
  actions.setConditionsConfig({
    value: conditionsConfig.value,
    flag: true,
    id: conditionsConfig1.value.id,
  })
  
  closeDrawer()
}

// 关闭抽屉
const closeDrawer = () => {
  actions.setCondition(false)
}
</script>

<style lang="less">
.condition_expression {
  .priority_level {
    position: absolute;
    top: 11px;
    right: 30px;
    width: 100px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(217, 217, 217, 1);
    font-size: 12px;
  }

  .condition_content {
    padding: 20px 20px 0;

    p.tip {
      margin: 20px 0;
      width: 100%;
      text-indent: 17px;
      line-height: 45px;
      background: rgba(241, 249, 255, 1);
      border: 1px solid rgba(64, 163, 247, 1);
      color: #46a6fe;
      font-size: 14px;
      border-radius: 4px;
    }

    .expression-input-section {
      margin-bottom: 24px;
    }
  }

  .demo-drawer__footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 20px;
    border-top: 1px solid #e4e7ed;
    margin-top: 20px;
  }
}

.clear:before,
.clear:after {
  content: ' ';
  display: table;
}

.clear:after {
  clear: both;
}
</style>